#############################################################################
# Copyright (c) 2009 Dmitry Grushin <dgrushin@gmail.com>.
#
# This file is part of clupower (cluster power manager utility)
#
# Clupower is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Clupower is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Clupower.  If not, see <http://www.gnu.org/licenses/>.
#
# Contributors:
#    Dmitry Grushin <dgrushin@gmail.com> - initial API and implementation
#############################################################################

require 'yaml'
require 'errors'
require 'singleton'
require 'algo'

$settings_path = nil
$settings_file = "clupower_settings.yml"

class Settings
  include Singleton

  def initialize
    load
  end

  def load
    set_list = []

    # Check if $settings_path is set
    if $settings_path
      set_list << $settings_path + File::SEPARATOR + $settings_file
    end
    # Check home folder
    set_list << ENV["HOME"] + File::SEPARATOR + $settings_file
    # Check global system setting folder
    set_list << File::SEPARATOR + "etc" + File::SEPARATOR + $settings_file

    for s in set_list
      if File.exist?(s)
        source = s
        break
      end
    end

    raise CPI7.new(set_list) unless source
    @config = YAML.load_file(source)

    set_algo
  end

  def get(option)
    value = @config[option]
    raise CPI9.new(option) if value == nil
    return value
  end

  def get_main_log_path
    get('CP_RUN_DIR') + File::SEPARATOR + "server.log"
  end

  def get_main_daemon_log_path
    get('CP_RUN_DIR') + File::SEPARATOR + "daemon.log"
  end

  def get_stats_file_path
    get('CP_RUN_DIR') + File::SEPARATOR + "stats.log"
  end

  def set_algo(aname = get('DEF_ALGO'))
    algo_class = PMA.get_subclasses[aname]
    if algo_class
      @pm_algo = algo_class.new
    else
      raise CPI1.new(aname)
    end
  end

  attr_accessor :config, :pm_algo
end